package com.sa07.ui.window;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import com.sa07.bean.TestItemBean;
import com.sa07.config.TestItemConfig;
import com.sa07.control.TestItemExecutor;
import com.sa07.db.OracleSessionFactory;
import com.sa07.ui.bean.Menu;
import com.sa07.ui.bean.MenuItem;
import com.sa07.ui.bean.StatusNameConstant;
import com.sa07.ui.bean.StatuslItem;
import com.sa07.ui.bean.TestBean;
import com.sa07.ui.bean.TestItemUiBean;
import com.sa07.ui.components.JloginInfoBar;
import com.sa07.ui.components.JstatusControl;
import com.sa07.ui.components.JtestJTable;
import com.sa07.ui.components.JtestResultContol;
import com.sa07.ui.components.JtestResultInfoBar;
import com.sa07.ui.config.MenuConfig;
import com.sa07.ui.config.StatusBarConfig;
import com.sa07.ui.enums.TestResult;
import com.sa07.ui.model.HistoryTestTableModel;
import com.sa07.ui.model.TestItemTableModel;
import com.sa07.ui.uitls.ControlContext;
import com.sa07.ui.uitls.UiTools;
import com.sa07.utils.StringUtils;

/**
 * 主窗体
 * 
 * @author Long.shangbo
 *
 * 2014-2-14 下午11:29:06
 */
public class MainFrame extends JFrame{
	
	private static final long serialVersionUID = -1603378586870420542L;
	
	private int initWidth = 900;
	
	private int initHeight = 650;
	
	private JMenuBar menuBar = null;
	
	private JButton autoTestBtn = null;
	
	private JButton customBtn = null;
	
	private JtestJTable testTable = null;
	
	private JTextField productCode = null;
	
	private TestItemExecutor executor = new TestItemExecutor();
	
	/**
	 * 是否为自动测试
	 */
	private boolean isAutoTest = true;
	
	public MainFrame(){
		setTitle("测试主窗口");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(new Dimension(initWidth, initHeight));
		setLocation(UiTools.getCenterPosition(initWidth, initHeight));
		setLayout(new BorderLayout());
	}
	
	/**
	 * 窗口启动
	 */
	public void launch(){
		//加载组件
		initComponents();
		//加载事件
		initListener();
		setExtendedState(MAXIMIZED_BOTH);
		setVisible(true);
		
	}
	
	/**
	 * 加载组件
	 */
	private void initComponents() {
		//初始化菜单
		initMenu();
		//初始化内容
		initContent();
		//初始化状态栏
		initLoginInfoBar();
	}
	
	private void initContent() {
		JPanel contentPanel = new JPanel(null);
		//获得屏幕尺寸
		Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		int x = 20;
		int y = 20;
		int marginTop = 10;
		
		//状态栏
		JPanel statusBar = initStatusBar();
		int statusHeight = 50;
		statusBar.setBounds(x, y, screenDim.width, statusHeight);
		contentPanel.add(statusBar);
		
		y += statusHeight + marginTop;
		
		//测试结果
		JPanel testResultBar = initTestResultInfo();
		int testResultBarHeight = 70;
		testResultBar.setBounds(x, y, 860, testResultBarHeight);
		contentPanel.add(testResultBar);
		
		y += testResultBarHeight + marginTop;
		
		//测试条形码
		JPanel testCodePanel = initTestCodePanel();
		int testCodeHeight = 25;
		testCodePanel.setBounds(x, y, screenDim.width, testCodeHeight);
		contentPanel.add(testCodePanel);
		
		y += testCodeHeight + marginTop;
		
		//测试结果
		JPanel testResultPanel = initTestResultPanel();
		int testResultHeight = 25;
		testResultPanel.setBounds(x, y, screenDim.width, testResultHeight);
		contentPanel.add(testResultPanel);
		
		y += testResultHeight + marginTop;
		int tableMargin = 10; 
		int marginBottom = 115;
		int testTableHeight = screenDim.height - y - marginBottom;
		
		//测试项表格
		JPanel testItemTablePanel = initTestItemTablePanel();
		int testTableWidth = (int)(screenDim.width * 2 / 3.3) - tableMargin;
		testItemTablePanel.setBounds(x, y, testTableWidth, testTableHeight);
		contentPanel.add(testItemTablePanel);
		
		x += testTableWidth + tableMargin;
		
		//历史记录表格
		JPanel historyTablePanel = initHistoryTablePanel();
		int hisTableWidth = screenDim.width - x; 
		historyTablePanel.setBounds(x, y, hisTableWidth, testTableHeight);
		contentPanel.add(historyTablePanel);
		
		add(contentPanel, BorderLayout.CENTER);
	}

	/**
	 * 测试结果
	 * @return
	 */
	private JPanel initTestResultPanel() {
		JPanel testResult = new JPanel();
		testResult.setLayout(null);
		int x = 0;
		int y = 0;
		int margin = 5;
		int testResultHeight = 25;
		
		JLabel testResultLbl = new JLabel("测试结果：");
		int testResultLblWidth = 80;
		testResultLbl.setBounds(x, y, testResultLblWidth, testResultHeight);
		testResult.add(testResultLbl);
		
		x += testResultLblWidth + margin;
		
		JtestResultContol testResultControl = new JtestResultContol();
		testResultControl.setBounds(x, y, JtestResultContol.defaultWidth, testResultHeight);
		testResult.add(testResultControl);
		
		return testResult;
	}

	/**
	 * 测试表格
	 * @return
	 */
	private JPanel initTestItemTablePanel() {
		JPanel testTablePanel = new JPanel();
		testTablePanel.setLayout(new GridLayout(1, 1));
		testTablePanel.setBorder(BorderFactory.createTitledBorder("测试项"));
		
		testTable = new JtestJTable(new TestItemTableModel());
		ControlContext.setTestItemTable(testTable);
		JScrollPane scrollPanel = new JScrollPane();
		scrollPanel.setViewportView(testTable);
		testTablePanel.add(scrollPanel);
		return testTablePanel;
	}
	
	/**
	 * 历史记录
	 * @return
	 */
	private JPanel initHistoryTablePanel() {
		JPanel historyTablePanel = new JPanel();
		historyTablePanel.setLayout(new GridLayout(1, 1));
		historyTablePanel.setBorder(BorderFactory.createTitledBorder("历史记录"));
		
		JtestJTable hisTable = new JtestJTable(new HistoryTestTableModel());
		JScrollPane scrollPanel = new JScrollPane();
		scrollPanel.setViewportView(hisTable);
		historyTablePanel.add(scrollPanel);
		return historyTablePanel;
	}

	/**
	 * 测试条形码
	 * @return
	 */
	private JPanel initTestCodePanel() {
		JPanel testCodePanel = new JPanel();
		testCodePanel.setLayout(null);
		
		int x = 0;
		int y = 0;
		int margin = 5;
		int proCodeHeight = 25;
		
		JLabel proCodeLbl = new JLabel("产品条形码：");
		int proCodeLblWidth = 80;
		proCodeLbl.setBounds(x, y, proCodeLblWidth, proCodeHeight);
		testCodePanel.add(proCodeLbl);
		
		x += proCodeLblWidth + margin;
		
		productCode = new JTextField();
		ControlContext.setCodeTxt(productCode);
		int productCodeWidth = 250;
		productCode.setBounds(x, y, productCodeWidth, proCodeHeight);
		testCodePanel.add(productCode);
		
		return testCodePanel;
	}
	
	/**
	 * 测试结果
	 * @return
	 */
	private JPanel initTestResultInfo() {
		return new JtestResultInfoBar();
	}

	/**
	 * 初始化状态栏
	 */
	private void initLoginInfoBar() {
		JPanel loginInfoBar = new JloginInfoBar();
		add(loginInfoBar, BorderLayout.SOUTH);
	}

	/**
	 * 初始化状态栏
	 */
	private JPanel initStatusBar() {
		List<StatuslItem> statusItems = StatusBarConfig.INSTANCE.getItemsList();
		JPanel statusBar = new JPanel(null);
		int x = 0;
		int y = 0;
		int statusWidth = 120;
		int statusHeight = 40;
		int margin = 10;
		ActionListener listener = null;
		if(statusItems != null && !statusItems.isEmpty()){
			Map<String, JstatusControl> statusControls = new HashMap<String, JstatusControl>();
			JstatusControl statusBtn = null;
			
			for(StatuslItem item : statusItems){
				statusBtn = new JstatusControl(item.getLabel());
				listener = getActionListener(item.getHandlerClass());
				if(item.isDisabled()){
					statusBtn.disabled();
				}
				if(listener != null ){
					statusBtn.addActionListener(listener);
				}
				
				statusBtn.setBounds(x, y, statusWidth, statusHeight);
				statusBar.add(statusBtn);
				statusControls.put(item.getName(), statusBtn);
				x += statusWidth + margin;
			}
			
			ControlContext.setStatusControls(statusControls);
		}
		
		int testBtnWidth = 80;
		autoTestBtn = new JButton("自动");
		autoTestBtn.setEnabled(false);
		x += 40;
		autoTestBtn.setBounds(x, y, testBtnWidth, statusHeight);
		statusBar.add(autoTestBtn);
		
		customBtn = new JButton("手动");
		x += 10 + testBtnWidth;
		customBtn.setBounds(x, y, testBtnWidth, statusHeight);
		statusBar.add(customBtn);
		return statusBar;
	}

	/**
	 * 初始化菜单
	 */
	private void initMenu() {
		menuBar = new JMenuBar();
		List<Menu> menus = MenuConfig.INSTANCE.getMenuConfig();
		
		if(menus != null && !menus.isEmpty()){
			JMenu menu = null;
			List<MenuItem> menuItems = null;
			JMenuItem menuItem = null;
			ActionListener listener = null;
			
			for(Menu m : menus){
				menu = new JMenu(m.getLabel());
				menuItems = m.getItems();
				
				if(menuItems != null && !menuItems.isEmpty()){
					for(MenuItem mi : menuItems){
						menuItem = new JMenuItem(mi.getLabel());
						listener = getActionListener(mi.getHandlerClass());
						
						if(listener != null){
							menuItem.addActionListener(listener);
						}
						menu.add(menuItem);
					}
				}
				menuBar.add(menu);
			}
		}
		
		setJMenuBar(menuBar);
	}
	
	/**
	 * 反射获得处理类实例
	 * @param handlerClass
	 * @return
	 */
	private ActionListener getActionListener(String handlerClass){
		if(StringUtils.isNullOrEmpty(handlerClass)) return null;
		
		try {
			@SuppressWarnings("unchecked")
			Class<? extends ActionListener> clazz = (Class<? extends ActionListener>) Class
					.forName(handlerClass);
			return clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * 加载事件
	 */
	private void initListener() {
		
		//自动测试按钮
		autoTestBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				isAutoTest = true;
				customBtn.setEnabled(true);
				autoTestBtn.setEnabled(false);
			}
		});
		
		//手动测试按钮
		customBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				isAutoTest = false;
				customBtn.setEnabled(false);
				autoTestBtn.setEnabled(true);
			}
		});
		
		//表格双击行事件
		testTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(isAutoTest){
					JOptionPane.showMessageDialog(null, "当前为自动测试模式，如需手动测试，请切换到手动测试模式!");
					return;
				}
				
				//如果非自动测试，则双击的时候进行测试
				if(e.getClickCount() == 2){
					//获得点击的行号
					int rowId  = testTable.rowAtPoint(e.getPoint());
					TestItemTableModel model = (TestItemTableModel)testTable.getModel();
					List<TestBean> testData = model.getData();
					TestItemUiBean testBean = (TestItemUiBean)testData.get(rowId);
					TestItemBean currTestItem = TestItemConfig.INSTANCE
									.getTestItemById(testBean.getTestId() - 1);
					TestResult res = executor.executeTest(currTestItem);
					testBean.setTestResult(res);
					model.refresh();
				}
			}
		});
	}

	/**
	 * 设置窗口最大化
	 */
	@SuppressWarnings("unused")
	private void setWindowMaxSize(){
		Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(screenDim);
	}
	
	/**
	 * 初始化
	 */
	public void init(){
		//检查MES设置
		new Thread((new Runnable() {			
			@Override
			public void run() {
				checkMes();
			}
		})).start();
		
		//填充测试表格
		fillTestItemTable();
	}

	/**
	 * 填充测试表格
	 */
	private void fillTestItemTable() {
		TestItemTableModel testModel = (TestItemTableModel)testTable.getModel();
		testModel.setDatas(TestItemConfig.INSTANCE.getTestUiItems());
		testTable.setRowSelectionInterval(0, 0);
		
	}

	/**
	 * 检查Mes设置
	 */
	private void checkMes() {

		JstatusControl mesControl = ControlContext.getStatusControls().get(StatusNameConstant.MES_NAME);
		mesControl.setTestResult(TestResult.PROCESS);
		boolean mesState = OracleSessionFactory.getFactory().createSession().testLink();
		if(mesState){
			mesControl.setTestResult(TestResult.SUCCESS);
		}else{
			mesControl.setTestResult(TestResult.FAILED);
		}
	}
}
